<template>
  <div class="box">
    <el-steps :active="steps" simple>
      <el-step icon="el-icon-edit" title="选择试卷"></el-step>
      <el-step icon="el-icon-upload" title="发布考试"></el-step>
    </el-steps>

    <div class="boxBottom">
      <div>
        <el-form label-position="left" label-width="110px">
          <el-form-item label="考试名称">
            <el-input v-model="form.examinationName" placeholder="请输入试卷名称" style="width: 88%"></el-input>
          </el-form-item>
          <el-form-item label="考试分类">
            <el-button style="border: 1px solid #409EFF" @click="classVisible=true">{{ test.examinationClassName }}<i
              class="el-icon-s-operation el-icon--right"></i></el-button>
          </el-form-item>
          <el-form-item label="考试时间">
            <el-date-picker
              v-model="form.testStartTime"
              placeholder="考试开始时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
            <span style="padding:10px;">到</span>
            <el-date-picker
              v-model="form.testEndTime"
              placeholder="考试结束时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="答卷时长">
            <el-radio-group v-model="answerTimeRadio">
              <el-radio :label="3">
                <el-input v-model="form.answerTime" :disabled="answerTimeRadio!=3" style="width: 70px;margin-right: 5px"
                          type="number"></el-input>
                分钟
              </el-radio>
              <el-radio :label="0">不限时长</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="答题次数">
            <el-radio-group v-model="answerNumberTimesRadio">
              <el-radio :label="0">无限次</el-radio>

              <el-radio :label="3">有限次
                <el-input v-if="answerNumberTimesRadio==3" v-model="form.answerNumberTimes"
                          style="width: 70px;margin-right: 5px;margin-left: 15px" type="number"></el-input>
                次
              </el-radio>

            </el-radio-group>
          </el-form-item>
          <el-form-item label="参与学员范围">

            <el-popover
              placement="bottom"
              trigger="click"
              width="200">
              <div class="popoverBox">
                <div
                  v-for="item in userList"
                  :key="item.userId" @click="isClickStatus(item)">
                  <span>
                    <i v-if="item.isClick" class="el-icon-check"></i>
                  </span>
                  {{ item.nickName }}
                </div>
              </div>
              <el-button slot="reference" style="border: 1px solid #409EFF">选择学员</el-button>
            </el-popover>
            <div v-if="userChangeList.length!=0" class="userChangeListStyle">
              <div v-for="item in userChangeList" class="item">{{ item.nickName }} <i class="el-icon-close"
                                                                                      @click="deleUserChangeList(item)"></i>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="考试封面">
            <el-upload
              :action="baseUrl + '/common/upload'"
              :before-upload="beforeAvatarUpload"
              :headers="{
                Authorization: `Bearer  ${this.$store.state.user.token}`,
              }"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              class="avatar-uploader">
              <img v-if="form.coverPicture" :src="form.coverPicture" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 10px"></div>
      <div>
        <div class="rightItem">
          <div class="rightTitle">

            <div>
              {{ questionDetail.examinationPaperSummaryName }}
            </div>
            <div>
              <el-button type="text" @click="goPreviewView">预览试卷</el-button> &nbsp;
              |
              <el-button type="text" @click="editTestPaper">编辑试卷</el-button>
            </div>

          </div>
          <div class="rightContent" style="padding-left: 15px">
            <div><span>总分：</span>{{ questionDetail.totalPoints }}</div>
            <div><span>创建人：</span>{{ questionDetail.createBy }}</div>
            <div><span>试题数量：</span>{{ questionDetail.totalPoints }}</div>
            <div><span>创建日期：</span>{{ questionDetail.createTime }}</div>
          </div>
        </div>
        <div class="rightItem">
          <div class="rightTitle">
            <div>
              考试说明
            </div>
            <div>
              <el-checkbox v-model="form.compulsoryReading" false-label="0" true-label="1">强制阅读考试说明
              </el-checkbox>
              <el-select v-model="form.compulsoryReadingTime" :disabled="form.compulsoryReading!=1" placeholder="请选择"
                         size="mini" style="width: 100px;margin: 0 8px">
                <el-option
                  v-for="item in timeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

            </div>
          </div>
          <div class="rightContent">
            <el-input
              v-model="form.remark"
              class="elTextarea"
              placeholder="请输入内容"
              resize="none"
              type="textarea">
            </el-input>
<!--            <el-input-->
<!--              v-model="form.explain"-->
<!--              class="elTextarea"-->
<!--              placeholder="请输入内容"-->
<!--              resize="none"-->
<!--              type="textarea">-->
<!--            </el-input>-->
          </div>
        </div>
        <el-button class="releaseBtn" @click="release">发布考试</el-button>
      </div>
    </div>

    <!--    试题分类-->
    <el-dialog
      :visible.sync="classVisible"
      center
      title="提示"
      width="30%">
      <div class="boxTree">
        <el-tree
          ref="elTree"
          :auto-expand-parent="false"
          :current-node-key="834"
          :data="treeData"
          :default-expand-all="false"
          :expand-on-click-node="true"
          :highlight-current="true"
          :props="defaultProps"
          node-key="id"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span v-if="data.reserve1 == 0" style="margin-right: 15px">{{
                node.label
              }}</span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="classVisible = false">取 消</el-button>
    <el-button type="primary" @click="changeNode">选择</el-button>
  </span>
    </el-dialog>
    <!--    试题分类-->


  </div>
</template>
<script>
import {addExamination, getExaminationDetail, listClassExamination, updateExamination} from "@/api/examination";
import {listUser} from "@/api/system/user";
import {mapGetters} from "vuex";
import {getSummary} from "@/api/examPaperLibrary";

export default {
  data() {
    return {
      steps: 2,
      form: {
        examinationName: '',
        answerTime: 60,
        answerNumberTimes: 10,
        coverPicture: null,
        testEndTime: null,
        testStartTime: null,
        compulsoryReading: 0,
        compulsoryReadingTime: null
      },
      test: {
        examinationClassName: '考试分类'
      },
      classVisible: false,

      defaultProps: {
        children: "children",
        label: "name",
      },
      treeData: [],
      beforClickData: {},
      answerTimeRadio: null,
      answerNumberTimesRadio: null,
      studentVisible: false,
      userList: [],
      value1: null,
      userChangeList: [],
      imageUrl: '',
      questionDetail: {},//试卷详情
      timeOption: [
        {label: '10秒', value: 10},
        {label: '20秒', value: 20},
        {label: '30秒', value: 30},
        {label: '1分钟', value: 60},
        {label: '2分钟', value: 120},
        {label: '3分钟', value: 180}]
    }
  },
  mounted() {
    this.getTreeList()
    if (this.$route.query.examinationId) {
      this.getExaminationDetail()
    } else {
      this.getUserList()

      this.getQuestionDetail()
    }


  },
  computed: {
    ...mapGetters(["baseUrl", "userId"]),
  }

  ,
  methods: {

    getTreeList() {
      listClassExamination().then((res) => {
        this.treeData = res.rows;
        this.init(this.treeData);
      });
    },
    init(data) {
      if (data.length === 0) return;
      for (let i = 0; i < data.length; i++) {
        if (typeof data[i] === "object" && data[i] !== null) {
          this.$set(data[i], "reserve1", 0);
        }
        if (Array.isArray(data[i].children) && data[i].children.length > 0) {
          this.init(data[i].children);
        }
      }
    },
    //点击树状图
    handleNodeClick(data, node) {
      this.beforClickData = data
    },
    changeNode() {
      this.test.examinationClassName = this.beforClickData.name
      this.form.examinationClassificationId = this.beforClickData.id
      this.classVisible = false
    },
    //查询用户
    async getUserList() {
      let obj = {
        pageSize: 999,
        pageNum: 1,
      };
      await listUser(obj).then((res) => {
        if (res.code == 200) {
          this.userList = res.rows;
          this.userList.map((item) => {
            this.$set(item, 'isClick', false)
          })
        }
      });
    },
    //查询考试详情
    getExaminationDetail() {
      getExaminationDetail(this.$route.query.examinationId).then((res) => {
        this.form = res.data
        this.questionDetail = res.data.examinationPaperSummary

        this.getUserList()
        //答卷时长
        if (res.data.answerTime) {
          this.answerTimeRadio = 3
        } else {
          this.answerTimeRadio = 0
        }
        //考试次数
        if (res.data.answerNumberTimes == '6666666666') {
          this.answerNumberTimesRadio = 0
        } else {
          this.answerNumberTimesRadio = 3
        }
        //参与学员范围
        this.userChangeList = res.data.examinationAndUserList.map(ele => {
          return {nickName: ele.sysUser.nickName, userId: ele.sysUser.userId}
        })
        setTimeout(() => {
          this.userList.forEach(ele => {
            if (this.userChangeList.some(item => item.userId == ele.userId)) {
              ele.isClick = true
            }
          })
        }, 300)


      })
    },
    //添加用户
    isClickStatus(val) {
      val.isClick = !val.isClick
      if (this.userChangeList.some(ele => ele.userId == val.userId)) {
        console.log('删除')
        this.userChangeList.splice(this.userChangeList.findIndex(ele => ele.userId == val.userId), 1)
      } else {
        this.userChangeList.push(val)
        console.log('添加')
      }

    },
    //删除选中用户
    deleUserChangeList(val) {
      this.userChangeList.splice(this.userChangeList.findIndex(ele => ele == val), 1)
      this.userList.forEach(ele => {
        if (ele == val) {
          ele.isClick = false
        }
      })
    },
    //考试封面上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.url
      this.form.coverPicture = res.url
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      return true
    },
    //获取试卷的详细信息
    getQuestionDetail() {
      let obj = {
        examinationPaperId: this.$route.query.id
      }
      getSummary(this.$route.query.id).then(res => {
        if (res.code == 200) {
          this.questionDetail = res.data
        }
      })

    },
    //预览试卷详情
    goPreviewView(val) {
      this.$router.push(
        "/examPaperLibrary/examPaperLibrary/management/previewView?examinationPaperSummaryId=" +
        this.$route.query.id
      );
    },
    //编辑试卷按钮
    editTestPaper(val) {
      console.log("编辑");
      this.$router.push(
        "/examPaperLibrary/examPaperLibrary/management/createTestPaper?examinationPaperSummaryId=" +
        this.$route.query.id
      );
    },
    //发布考试
    release() {
      console.log(this.form)
      if (this.form.examinationName == '') {
        this.$message.warning('请输入考试名称')
        return
      }
      if (this.form.examinationClassificationId == null) {
        this.$message.warning('请选择考试分类')
        return
      }
      if (this.form.testStartTime == null) {
        this.$message.warning('请选择考试开始时间')
        return
      }
      if (this.form.testEndTime == null) {
        this.$message.warning('请选择考试结束时间')
        return
      }
      if (this.answerTimeRadio == 3 || this.answerTimeRadio == null) {
        if (this.form.answerTime == null) {
          this.$message.warning('请选择考试时长')
          return
        }
      }
      if (this.answerNumberTimesRadio == null) {
        this.$message.warning('请选择答题次数')
        return
      }
      if (this.answerNumberTimesRadio == 0) {
        this.form.answerNumberTimes = 6666666666
      }
      if (this.userChangeList.length == 0) {
        this.$message.warning('请选择考试对象')
        return
      }
      this.form['examinationAndUserList'] = this.userChangeList.map(ele => {
        return {userId: ele.userId}
      })
      if (this.form.coverPicture == null) {
        this.form.coverPicture = 'https://file.51150.shop/tupian/Snipaste_2024-06-13_10-47-47_20240613104800A002.png'
      }
      if (this.form.compulsoryReading == 1) {
        if (this.form.compulsoryReadingTime == null) {
          this.$message.warning('请输入阅读时长')
          return
        }
      }
      this.form['examinationPaperSummaryId'] = this.$route.query.id

      if (this.form.examinationId) {
        delete this.form.examinationPaperSummary
        updateExamination(this.form).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message.success('修改成功')
            this.$router.push('/examination/index')
          }
        })
      } else {

        addExamination(this.form).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message.success('发布成功')
            this.$router.push('/examination/index')
          }
        })
      }


    },


  }
}
</script>
<style lang="scss" scoped>
.box {
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: #f1f3f8;

  > .el-steps {
    background-color: white;
    height: 80px;
  }

  .boxBottom {
    height: 800px;
    display: flex;
    margin: 0 15px;
    padding: 15px;
    background-color: white;

    > div:nth-of-type(1) {
      flex: 1;
    }

    > div:nth-of-type(3) {
      flex: 1;
    }
  }
}

.popoverBox {
  height: 200px;

  overflow: auto;

  > div {
    padding: 5px 10px;
    cursor: pointer;
    display: flex;

    > span {
      width: 20px;
    }
  }

  > div:hover {
    background-color: #409EFF;
    color: white;
  }

}

.userChangeListStyle {
  min-height: fit-content;
  background-color: #f1f3f8;
  margin-top: 10px;
  padding: 5px;
  padding-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border-radius: 10px;
  flex-wrap: wrap;
  max-height: 100px;
  overflow: auto;

  > .item {
    padding: 0 10px;
    background-color: white;
    font-size: 14px;
    border-radius: 5px;
    margin-left: 8px;
    margin-bottom: 5px;

    > .el-icon-close {
      font-weight: bold;
    }
  }
}

//右侧考试说明
.rightItem {
  height: 200px;
  border: 1px solid #d9d9d9;
  margin-bottom: 10px;
  border-radius: 10px;

  .rightTitle {
    height: 50px;
    background-color: #eee;
    line-height: 50px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .rightContent {
    height: calc(100% - 50px);
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    font-size: 14px;

    .elTextarea {
      height: 100%;

      ::v-deep .el-textarea__inner {
        height: 100%;
      }
    }

    span {
      color: #6d737b;
    }
  }
}


//图片上传
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.releaseBtn {
  background-color: #E6A23C;
  color: white;
  float: right;
}
</style>
